package com.wn.servlet;

import com.alibaba.fastjson.JSON;
import com.wn.bean.Owner;
import com.wn.service.OwnerService;
import com.wn.service.impl.OwnerServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author yellow Docter
 * @date 2024 -06-18
 * @desc
 *
 *    01 servlet 开发的步骤
 *        01 创建一个类 继承HttpServlet
 *        02 重写 doGet\doPost方法
 *                 doGet 中调用doPost
 *                 统一在doPost中处理请求
 *
 *        03  写业务逻辑 拿到数据 xxx
 *        04  配置 @WebServlet("处理请求的url")
 */
@WebServlet("/owner/update")
public class OwnerUpdateServlet extends HttpServlet {

    private OwnerService ownerService = new OwnerServiceImpl();
    //doGet 处理get请求
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
//
//    //doPost 处理post请求
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //处理中文乱码
        // 设置请求数据的编码: UTF-8
        req.setCharacterEncoding("UTF-8");   //网页传递过来的数据的编码

        resp.setContentType("text/html;charset=UTF-8");  //服务器给浏览器回写的数据的编码

        //通过  req 获取数据
        String id = req.getParameter("id");
        String username = req.getParameter("username");
        String tel = req.getParameter("tel");
        String sex = req.getParameter("sex");
        String identity = req.getParameter("identity");
        String houseId = req.getParameter("houseId");
        String remarks = req.getParameter("remarks");


        Owner owner = new Owner();
        owner.setId(Integer.parseInt(id));
        owner.setUsername(username);
        owner.setTel(tel);
        owner.setSex(Integer.parseInt(sex));
        owner.setIdentity(identity);
        owner.setHouseId(Integer.parseInt(houseId));
        owner.setRemarks(remarks);

        System.out.println("owner = " + owner);

        //jdbc 操作 可以吗?
        boolean row = ownerService.updateOwner(owner);

        // 返回数据
        Map<String,Object> result = new HashMap<>();
        result.put("code",row ? "200" :"2000");
        result.put("msg",row ? "修改成功":"修改失败");
        //使用json框架 可以直接把java对象转成 json 字符串
        String jsonString = JSON.toJSONString(result);
        resp.getWriter().write(jsonString);

    }
}
